package org.apache.rocketmq.client.impl.factory;

import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;
import org.apache.rocketmq.remoting.RPCHook;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: jiaxiangen
 * @Date: 2025/6/16 16:46
 * @Version 1.0
 * @Description: 客户端管理器
 */
public class MQClientManager {

    private final static Logger log = LoggerFactory.getLogger(MQClientManager.class);

    private static MQClientManager singleton = new MQClientManager();

    private AtomicInteger factoryIndexGenerator = new AtomicInteger();

    //
    private ConcurrentMap<String, MQClientInstance> factoryTable = new ConcurrentHashMap<String, MQClientInstance>();

    private MQClientManager() {
    }

    public static MQClientManager getInstance() {
        return singleton;
    }
    public MQClientInstance getOrCreateMQClientInstance(final ClientConfig clientConfig) {
        return getOrCreateMQClientInstance(clientConfig, null);
    }

    /**
     * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
     * @author：陈清风扬，个人微信号：chenqingfengyangjj。
     * @date:2025/1/15
     * @方法描述：创建控制台客户端的方法
     */
    public MQClientInstance getOrCreateMQClientInstance(final ClientConfig clientConfig, RPCHook rpcHook) {
        String clientId =  clientConfig.buildMQClientId();
        MQClientInstance mqClientInstance = factoryTable.get(clientId);
        if (null == mqClientInstance) {
            mqClientInstance = new MQClientInstance(clientConfig,
                    factoryIndexGenerator.getAndIncrement(), clientId, rpcHook);
            MQClientInstance prev = factoryTable.putIfAbsent(clientId, mqClientInstance);
            if (prev != null) {
                mqClientInstance = prev;
                log.warn("Returned Previous MQClientInstance for clientId:[{}]", clientId);
            } else {
                log.info("Created new MQClientInstance for clientId:[{}]", clientId);
            }
        }
        return mqClientInstance;

    }


    public void removeClientFactory(final String clientId) {
        this.factoryTable.remove(clientId);
    }


}
